package com.konsung.ksdc.common.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;

import java.sql.SQLException;

/**
 * 数据库类
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String TABLE_NAME = "ksdc.db";

    /**
     * 构造方法
     * @param context 上下文
     */
    private DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, MqttMsgBean.class);
            TableUtils.createTable(connectionSource, MqttMsgNotice.class);
            TableUtils.createTable(connectionSource, GroupNetBean.class);
            TableUtils.createTable(connectionSource, RegisterUserNetBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int
            oldVersion, int newVersion) {

        onCreate(database, connectionSource);
    }

    private static DatabaseHelper instance;

    /**
     * 单例获取该Helper
     * @param context 上下文
     * @return 对象
     */
    public static synchronized DatabaseHelper getHelper(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null) {
                    instance = new DatabaseHelper(context);
                }
            }
        }

        return instance;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();
    }
}
